package cn.ultrarisk.scadmin.manager.biz.user.service;

import cn.ultrarisk.scadmin.manager.biz.common.context.OperationType;
import cn.ultrarisk.scadmin.manager.biz.common.service.OperationLogService;
import cn.ultrarisk.scadmin.manager.biz.user.dao.RoleDAO;
import cn.ultrarisk.scadmin.manager.biz.user.entity.Role;
import cn.ultrarisk.scadmin.manager.exception.BizCheckedException;
import cn.ultrarisk.mybatis.extension.query.Updater;
import cn.ultrarisk.scadmin.manager.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 角色数据操作类
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/3/28
 * @since V1.0
 */
@Service
@Transactional(propagation = Propagation.REQUIRED)
public class RoleService {
    @Autowired
    private RoleDAO roleDAO;
    @Autowired
    private OperationLogService operationLogService;

    public void create(String name, List<Integer> privilegeIds) {
        if (StringUtil.isEmpty(name)) {
            throw new BizCheckedException("the role's name can't be empty");
        }
        if (roleDAO.getByName(name, null) != null) {
            throw new BizCheckedException(String.format("the name[%s] allready exist", name));
        }
        Role role = new Role();
        role.setName(name);
        roleDAO.create(role);
        roleDAO.createPrivilegeRelation(role.getId(), privilegeIds);
        operationLogService.createRoleLog(OperationType.ROLE_CREATE, role.getId());
    }

    public void update(Integer id, String name, List<Integer> privilegeIds) {
        if (StringUtil.isEmpty(name)) {
            throw new BizCheckedException("the role's name can't be empty");
        }
        Role role = roleDAO.get(id);
        if (role == null) {
            throw new BizCheckedException("the role is not exist");
        }
        roleDAO.update(id, Updater.update(Role.NAME, name));
        roleDAO.deletePrivilegeAsso(role.getId());
        roleDAO.createPrivilegeRelation(role.getId(), privilegeIds);
        operationLogService.createRoleLog(OperationType.ROLE_UPDATE, id);
    }

    public void delete(Integer id) {
        operationLogService.createRoleLog(OperationType.ROLE_DELETE, id);
        roleDAO.delete(id);
    }
}